const express = require('express')
const app = express()
const cors = require('cors')
const multer = require('multer')
const path = require('path')
const { db } = require('./src/database/index')
const bodyParser = require('body-parser')

app.use(cors())
// 正文解析
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

// 验证token
const ADMIN_TOKEN_PATH = '/_token'
app.all('*', async (req, res, next) => {
  if (req.path.indexOf(ADMIN_TOKEN_PATH) > -1) {
    let { token } = req.headers;
    const sqlSelectTokenStr = `SELECT * 
                FROM 
                managers 
                WHERE token = '${token}'`;

    const outToken = await db.async(sqlSelectTokenStr);
    if (outToken.err || outToken.length == 0) {
      return res.send({
        status: {
          code: 403,
          msg: '未登陆',
        },
        data: 'null'
      })
    } else {
      next();
    }
  } else {
    next();
  }

})

// 上传功能
const update = multer({
  dest: './public/upload/temp'
})
app.use(update.any())

// 静态资源
app.use(express.static(path.join(__dirname, 'public')))

// 结果处理中间件
app.use((req, res, next) => {
  res.jgcl = function (msg, code = 200, data) {
    res.send({
      status: {
        code,
        msg: msg ? msg : 'success'
      },
      data: data ? data : 'null'
    })
  }
  next()
})

app.all('/', (req, res) => {
  res.send('欢迎使用个人博客服务器！')
})

// 路由
// 测试
app.use(require('./src/router/test'))

// 登录与注册
app.use(require('./src/router/loginRouter'))

// 分类
app.use('/category', require('./src/router/categoryRouter'))

// 文章
app.use('/article', require('./src/router/articleRouter'))

// 上传
app.use('/upload', require('./src/router/uploadRouter'))



app.listen('8080', () => {
  console.log('欢迎使用个人博客服务器：http://localhost:8080');
})